package com.example.xd.myapplication;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Interceptor;
import com.alibaba.android.arouter.facade.callback.InterceptorCallback;
import com.alibaba.android.arouter.facade.model.RouteMeta;
import com.alibaba.android.arouter.facade.template.IInterceptor;
import com.alibaba.android.arouter.launcher.ARouter;
import com.example.xd.commen.ARouterPath;
import com.example.xd.commen.MainLooper;
import com.example.xd.commen.annotation.OrangeProcess;
import com.example.xd.commen.annotation.PrivilegeProcess;
import com.example.xd.model_net.NetActivity;

import java.lang.reflect.Field;
import java.util.Map;

import pub.devrel.easypermissions.EasyPermissions;


/**
 * @auther XuDan on 2019/6/18.
 */
@Interceptor(priority = 4, name = "普通权限拦截")
public class PermissionIntercepter implements IInterceptor {
    Context mContext;

    @Override
    public void process(Postcard postcard, InterceptorCallback callback) {
        switch (postcard.getPath()) {
            case ARouterPath.NetActivity_path:
                Bundle extras = postcard.getExtras();
                String text = extras.getString("text");
                Log.i("xd-----------", text);
//                String[] s = {Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                        Manifest.permission.READ_EXTERNAL_STORAGE};
//                testNetActivity(postcard, callback);
//                String[] net_permission = PrivilegeProcess.getPermissions("com.example.xd.model_net.NetActivity");
                String[] net_permission = PrivilegeProcess.getPermissions(getClazz(postcard));
                if (null != net_permission && net_permission.length > 0) {
                    if (EasyPermissions.hasPermissions(mContext, net_permission)) {
                        callback.onContinue(postcard);
                    } else {
                        ARouter.getInstance().build("/myapplication/PermissionTestActivity")
                                .withCharSequenceArray("permission", net_permission)
                                .withString("path", ARouterPath.NetActivity_path)
                                .withBundle("extras", extras)
                                .navigation(mContext);
                    }
                } else {
                    callback.onContinue(postcard);
                }
                break;
            case ARouterPath.PermissionActivity_Path:
                Log.i("xd-----", "/model_permission/PermissionActivity");
                testPermissionActivity(postcard, callback);

                break;
            case ARouterPath.Main_path:
//                String[] main_permission = {Manifest.permission.WRITE_CONTACTS,
//                        Manifest.permission.READ_CONTACTS};
//                String[] main_permission = PrivilegeProcess.getPermissions("com.example.xd.myapplication.MainActivity");
                String[] main_permission = PrivilegeProcess.getPermissions(getClazz(postcard));
                if (null != main_permission && main_permission.length > 0) {
                    if (EasyPermissions.hasPermissions(mContext, main_permission)) {
                        callback.onContinue(postcard);
                    } else {
                        ARouter.getInstance().build("/myapplication/PermissionTestActivity")
                                .withCharSequenceArray("permission", main_permission)
                                .withString("path", ARouterPath.Main_path)
                                .withBundle("extras", postcard.getExtras())
                                .navigation(mContext);
                    }
                } else {
                    callback.onContinue(postcard);

                }
                break;
            case ARouterPath.CacheActivity_Path:
//                String[] catch_permission = {Manifest.permission.WRITE_CALENDAR,
//                        Manifest.permission.READ_CALENDAR};
//                String[] catch_permission = PrivilegeProcess.getPermissions("com.example.xd.model_cache.CacheActivity");
                String[] catch_permission = PrivilegeProcess.getPermissions(getClazz(postcard));
                if (null != catch_permission && catch_permission.length > 0) {
                    if (EasyPermissions.hasPermissions(mContext, catch_permission)) {
                        callback.onContinue(postcard);
                    } else {
                        ARouter.getInstance().build("/myapplication/PermissionTestActivity")
                                .withCharSequenceArray("permission", catch_permission)
                                .withString("path", ARouterPath.CacheActivity_Path)
                                .withBundle("extras", postcard.getExtras())
                                .navigation(mContext);
                    }
                } else {
                    callback.onContinue(postcard);

                }
                break;
            case ARouterPath.VideoActivity_Path:
//                String[] video_permission = PrivilegeProcess.getPermissions("com.example.xd.model_video.VideoActivity");
                String[] video_permission = PrivilegeProcess.getPermissions(getClazz(postcard));
                if (null != video_permission && video_permission.length > 0) {
                    if (EasyPermissions.hasPermissions(mContext, video_permission)) {
                        callback.onContinue(postcard);
                    } else {
                        ARouter.getInstance().build("/myapplication/PermissionTestActivity")
                                .withCharSequenceArray("permission", video_permission)
                                .withString("path", ARouterPath.VideoActivity_Path)
                                .withBundle("extras", postcard.getExtras())
                                .navigation(mContext);
                    }
                } else {
                    callback.onContinue(postcard);

                }
                break;
            default:
                callback.onContinue(postcard);
                break;
        }
    }

    private void testPermissionActivity(Postcard postcard, InterceptorCallback callback) {
        final AlertDialog.Builder ab = new AlertDialog.Builder(NetActivity.getThis());
        ab.setCancelable(false);
        ab.setTitle("温馨提醒");
        ab.setMessage("想要跳转到PermissionActivity么？(触发了\"/model_permission/PermissionActivity\"拦截器，拦截了本次跳转)");
        ab.setNegativeButton("继续", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                callback.onContinue(postcard);
            }
        });
        ab.setNeutralButton("算了", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                callback.onInterrupt(null);
            }
        });
        ab.setPositiveButton("加点料", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                postcard.withString("extra", "我是在拦截器中附加的参数");
                callback.onContinue(postcard);
            }
        });

        MainLooper.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ab.create().show();
            }
        });
    }

    private void testNetActivity(Postcard postcard, InterceptorCallback callback) {
        String[] permissions = PrivilegeProcess.getPermissions("com.example.xd.myapplication.MainActivity");
        if (null != permissions && permissions.length > 0) {
            for (int i = 0; i < permissions.length; i++) {
                Log.i("permissions---", permissions[i]);
            }
        }
        OrangeProcess.getOrange("com.example.xd.myapplication.MainActivity");
        MainLooper.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mContext, "/model_net/NetActivity", Toast.LENGTH_SHORT).show();
            }
        });
        callback.onContinue(postcard);
    }

    @Override
    public void init(Context context) {
        Log.i("xd------", "初始化拦截器4");
        mContext = context;
    }

    public Class getClazz(Postcard postcard) {
        Map<String, RouteMeta> routes = null;
        if (routes == null) {
            Class<?> aClass = null;
            try {
                aClass = Class.forName("com.alibaba.android.arouter.core.Warehouse");
                Field routes1 = aClass.getDeclaredField("routes");
                routes1.setAccessible(true);
                routes = (Map<String, RouteMeta>) routes1.get(null);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        RouteMeta routeMeta = routes.get(postcard.getPath());
        Class activityClass = routeMeta.getDestination();
        return activityClass;
    }

}
